package com.yinhai.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.lz.util.Utils;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.LoginTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.constant.UrlConstant;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginValidateActivity extends Activity {

	private EditText userName;
	private EditText password;
	private Button btn,btnsy;
	private Button cancle;
	private Context context;
	AlertDialog.Builder dialog;
	private long exitTime = 0;
	private AQuery aq = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		aq = new AQuery(this);
		setContentView(R.layout.main_login_validate_new);
		userName = (EditText) this.findViewById(R.id.userName);
//		password = (EditText) this.findViewById(R.id.password);
		aq.id(R.id.head_btn_back).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
		btn = (Button) this.findViewById(R.id.btn);
		btnsy = (Button)this.findViewById(R.id.btnsy);
		cancle = (Button) this.findViewById(R.id.cancle);
		
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String userNameStr = userName.getText() == null ? "" : userName
						.getText().toString().trim();
				if(userNameStr.equals("")){
					Utils.showToast(context, "电话号码不能为空！");
					return;
				}
				 
				if (isMobileNO(userNameStr)) {
					
					
					if (userNameStr.length() > 4) {
						Intent it = new Intent(context, LoginValidateYZM.class);
						it.putExtra("USERNAME", userNameStr);
						startActivity(it);
					}  
						
					
				} else {
					Toast.makeText(context, "请输入正确的手机号码",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		/**
		 * 限制输入框换行
		 */
		userName.setOnEditorActionListener(new OnEditorActionListener() {            
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
            	if(event == null) {
            		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
                    if(inputMethodManager.isActive()){  
                        inputMethodManager.hideSoftInputFromWindow(LoginValidateActivity.this.getCurrentFocus().getWindowToken(), 0);
                    }  
            		return true;
            	}
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
		});
		
		btnsy.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String userNameStr = userName.getText() == null ? "" : userName
						.getText().toString().trim();
				/*String passwordStr = password.getText() == null ? "123123" : password
						.getText().toString().trim();*/
				if (userNameStr.length() > 0 ) {
					if (isMobileNO(userNameStr)) {
						if (userNameStr.length() > 4) {
								LoginTask loginTask = new LoginTask(context);
								AsyncTaskParam taskParam = new AsyncTaskParam(
										UrlConstant.LOCAL_URI
												+ UrlConstant.TEMPCHECK);
								List<NameValuePair> list = new ArrayList<NameValuePair>();
								NameValueParam user_phone = new NameValueParam();
								//NameValueParam first = new NameValueParam();
								/*first.setName("first");
								// 第一次登录验证
								first.setValue("0");*/
								user_phone.setName("phone");
								user_phone.setValue(userName.getText() == null ? ""
										: userName.getText().toString().trim());
								//list.add(first);
								list.add(user_phone);
								taskParam.setPostParam(list);
								loginTask.execute(taskParam);
							
						} 

					} else {
						Toast.makeText(context, "请输入正确的手机号码",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(context, "手机号码不能为空", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});
		
		
		
		
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

				dialog = new AlertDialog.Builder(LoginValidateActivity.this);

				dialog.setTitle("提示")
						.setIcon(android.R.drawable.ic_dialog_info)
						.setMessage("确认退出！")
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();

									}
								})
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										android.os.Process
												.killProcess(android.os.Process
														.myPid());
									}
								}).create();
				dialog.show();

			}
		});
		registerReceiver(loginreceiver,new IntentFilter("com.gaa.login"));
	}
	private BroadcastReceiver loginreceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("com.gaa.login")) {
				finish();
			}
			
		}
	};
	@Override
	public void onDestroy() {
		unregisterReceiver(loginreceiver);
		super.onDestroy();
	}
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
//		return m.matches();
		if(mobiles.length() == 11) {
			return true;
		} else {
			return false;
		}
	}
	
/*	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
	   if(event.getAction()==KeyEvent.ACTION_DOWN&&event.getKeyCode()==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0) {
		   exit();
          return true;
	   }
	   return super.dispatchKeyEvent(event);
	}
	public void exit(){
		if((System.currentTimeMillis()-exitTime) > 2000){   
		    Toast toast = Toast.makeText(getApplicationContext(), "再按一次后退键退出应用程序", Toast.LENGTH_SHORT);
		    toast.setGravity(Gravity.CENTER, 0, 0);
		    toast.show();
		    exitTime = System.currentTimeMillis();    
		}else{   
			android.os.Process
			.killProcess(android.os.Process
					.myPid());
		}
	}*/
	
	
	
}
